package com.alibaba.travel.comment.config;

import com.alibaba.travel.article.config.JacksonObjectMapper;
import com.alibaba.travel.comment.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: where
 * @Date: 2023/02/28/8:48
 * @Description: 配置
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    String[] patterns = {
            "/login",
            "/logout",
            "/css/**",
            "/js/**",
            "/index.html",
            "favicon.ico",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources/**",
            "/v2/api-docs/**"};
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        List<String> collect = Arrays.stream(patterns).collect(Collectors.toList());
        // 添加登录拦截器， 配置路径白名单
        registry.addInterceptor(loginInterceptor()).excludePathPatterns(collect);
    }

    /**
     * 拦截器加载的时间点在springcontext之前，即在bean实例化之前
     * 所以不能用@Autowired注解， 应当先进行实例化
     * @return
     */
    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器，底层使用Jackson将Java对象转为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器对象追加到mvc框架的转换器集合中
        converters.add(0,messageConverter);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }

}
